package com.yami.shop.seckill.multishop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.vo.SeckillVO;
import com.yami.shop.bean.enums.EsOperationType;
import com.yami.shop.bean.enums.OfflineHandleEventType;
import com.yami.shop.bean.enums.ProdType;
import com.yami.shop.bean.enums.StationEnum;
import com.yami.shop.bean.event.EsProductUpdateEvent;
import com.yami.shop.bean.model.OfflineHandleEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.Sku;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.SkuMapper;
import com.yami.shop.seckill.common.dto.SeckillPageDto;
import com.yami.shop.seckill.common.enums.SeckillEnum;
import com.yami.shop.seckill.common.model.Seckill;
import com.yami.shop.seckill.common.model.SeckillSku;
import com.yami.shop.seckill.common.service.SeckillService;
import com.yami.shop.seckill.common.service.SeckillSkuService;
import com.yami.shop.seckill.multishop.dto.SeckillProdDto;
import com.yami.shop.seckill.multishop.param.SeckillParam;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.OfflineHandleEventService;
import com.yami.shop.service.ProductService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import com.yami.shop.common.util.BeanUtil;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 秒杀信息
 *
 * @author LGH
 * @date 2019-08-28 09:36:59
 */
@RestController
@AllArgsConstructor
@RequestMapping("/seckill/seckill")
@Tag(name = "商家端秒杀信息接口")
public class SeckillController {

    private final SeckillService seckillService;



    private final ProductService productService;

    private final ApplicationEventPublisher eventPublisher;

    private final SeckillSkuService seckillSkuService;

    private final OfflineHandleEventService offlineHandleEventService;

    private final SkuMapper skuMapper;

    @GetMapping("/page")
    @Operation(summary =  "分页查找秒杀信息")
    public ServerResponseEntity<IPage<SeckillPageDto>> getSeckillPage(PageParam<Seckill> page, @ParameterObject SeckillVO seckill) {
        seckill.setShopId(SecurityUtils.getShopUser().getShopId());
        seckill.setLang(I18nMessage.getDbLang());
        IPage<SeckillPageDto> pageSeckill = seckillService.pageSeckill(page, seckill);
        return ServerResponseEntity.success(pageSeckill);
    }

    @GetMapping("/info/{seckillId}")
    @Operation(summary =  "通过id查询秒杀信息")
    @Parameter(name = "seckillId", description = "秒杀id", required = true)
    public ServerResponseEntity<SeckillProdDto> getById(@PathVariable("seckillId") Long seckillId) {
        Seckill seckill = seckillService.getById(seckillId);
        if (!Objects.equals(SecurityUtils.getShopUser().getShopId(), seckill.getShopId())) {
            throw new YamiShopBindException("yami.no.auth");
        }
        SeckillProdDto dto = new SeckillProdDto();
        dto.setSeckill(seckill);
        Product product = productService.getProductAndLang(seckill.getProdId());
        dto.setProd(product);
        dto.setSeckillSkus(seckillSkuService.listSeckillSkuBySeckillId(seckillId));
        return ServerResponseEntity.success(dto);
    }

    @PostMapping
    @PreAuthorize("@pms.hasPermission('seckill:seckill:save')")
    @Operation(summary =  "新增秒杀信息")
    public ServerResponseEntity<Void> save(@RequestBody @Valid SeckillParam seckillParam) {
        Seckill seckill = BeanUtil.map(seckillParam, Seckill.class);
        if(Objects.isNull(seckill.getMaxNum())||Objects.equals(seckill.getMaxNum(),0)){
            //请输入限购数量
            throw new YamiShopBindException("yami.seckill.input.maxNum");
        }
        long prodCount = productService.count(new LambdaQueryWrapper<Product>()
                .eq(Product::getShopId, SecurityUtils.getShopUser().getShopId())
//                .and(wrapper -> wrapper.isNull(Product::getGroupActivityId).or().eq(Product::getGroupActivityId, 0))
//                .and(wrapper -> wrapper.isNull(Product::getSeckillActivityId).or().eq(Product::getSeckillActivityId, 0))
                .and(wrapper -> wrapper.isNull(Product::getProdType).or().eq(Product::getProdType, ProdType.PROD_TYPE_NORMAL).or().eq(Product::getProdType, ProdType.PROD_TYPE_SECKILL))
                .eq(Product::getProdId, seckillParam.getProdId()));
        if (prodCount == 0) {
            // 商品无法参与秒杀活动
            throw new YamiShopBindException("yami.seckill.prod");
        }
        List<SeckillSku> seckillSkus = seckillParam.getSeckillSkus();
        List<Long> skuIds = seckillSkus.stream().map(SeckillSku::getSkuId).collect(Collectors.toList());
        List<Sku> skuList = skuMapper.getSkuBySkuIds(skuIds);
        Map<Long, Integer> skuStatusMap = skuList.stream().collect(Collectors.toMap(Sku::getSkuId, Sku::getStatus));
        Integer seckillTotalStocks = 0;
        double seckillPrice = Double.MAX_VALUE;
        for (SeckillSku seckillSku : seckillSkus) {
            //禁用状态的sku不能参与秒杀活动
            if(skuStatusMap.get(seckillSku.getSkuId()) == 0){
                continue;
            }
            seckillTotalStocks += seckillSku.getSeckillStocks();
            seckillPrice = Math.min(seckillPrice, seckillSku.getSeckillPrice());
            //修改sku状态
            Sku sku = new Sku();
            sku.setSkuId(seckillSku.getSkuId());
            sku.setStatus(seckillSku.getStatus());
            sku.setPic(seckillSku.getPic());
            skuMapper.updateSkuById(sku);
        }
        if(seckillTotalStocks == 0){
            // 商品无法参与秒杀活动
            throw new YamiShopBindException("yami.seckill.prod");
        }
        // 库存
        seckill.setSeckillOriginStocks(seckillTotalStocks);
        seckill.setSeckillTotalStocks(seckillTotalStocks);
        // 配置店铺id
        seckill.setShopId(SecurityUtils.getShopUser().getShopId());
        seckill.setProdId(seckillParam.getProdId());
        seckill.setSeckillPrice(seckillPrice);
        seckillService.saveSeckill(seckill, seckillSkus);
        // 清除缓存
        productService.removeProdCacheByProdId(seckillParam.getProdId());
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        seckillService.removeSeckillCache(seckill.getSeckillId(), seckill.getProdId());
        eventPublisher.publishEvent(new EsProductUpdateEvent(seckill.getProdId(), null, EsOperationType.UPDATE));
        return ServerResponseEntity.success();
    }

    @PutMapping("/invalid/{seckillId}")
    @PreAuthorize("@pms.hasPermission('seckill:seckill:invalid')")
    @Operation(summary =  "通过id使秒杀商品失效")
    @Parameter(name = "seckillId", description = "秒杀id", required = true)
    public ServerResponseEntity<Void> invalidById(@PathVariable Long seckillId) {
        Seckill seckill = seckillService.getById(seckillId);
        if (!SecurityUtils.getShopUser().getShopId().equals(seckill.getShopId())) {
            throw new YamiShopBindException(ResponseEnum.UNAUTHORIZED);
        }
        if (Objects.equals(seckill.getStatus(), SeckillEnum.OFFLINE.getValue())) {
            throw new YamiShopBindException("yami.seckill.cannot.invalid");
        }
        seckillService.invalidById(seckill);
        productService.removeProdCacheByProdId(seckill.getProdId());
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        seckillService.removeSeckillCache(seckill.getSeckillId(), seckill.getProdId());
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/{seckillId}")
    @PreAuthorize("@pms.hasPermission('seckill:seckill:delete')")
    @Operation(summary =  "通过id删除秒杀信息")
    @Parameter(name = "seckillId", description = "秒杀id", required = true)
    public ServerResponseEntity<Void> removeById(@PathVariable Long seckillId) {
        Seckill seckill = seckillService.getById(seckillId);
        Integer oldStatus = seckill.getStatus();
        if (Objects.equals(StationEnum.NORMAL.getValue(), seckill.getStatus())) {
            // 秒杀活动未关闭，无法删除
            throw new YamiShopBindException("yami.seckill.cannot.delete");
        }
        seckillService.invalidById(seckill);
        seckill.setIsDelete(1);
        seckill.setStatus(oldStatus);
        seckillService.updateById(seckill);
        productService.removeProdCacheByProdId(seckill.getProdId());
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        seckillService.removeSeckillCache(seckill.getSeckillId(), seckill.getProdId());
        return ServerResponseEntity.success();
    }

    @GetMapping("/getOfflineHandleEventBySeckillId/{seckillId}")
    @Operation(summary =  "通过活动id获取下线信息")
    @Parameter(name = "seckillId", description = "秒杀id", required = true)
    public ServerResponseEntity<OfflineHandleEvent> getOfflineHandleEventBySeckillId(@PathVariable("seckillId") Long seckillId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.SECKILL.getValue(), seckillId);
        return ServerResponseEntity.success(offlineHandleEvent);
    }

    @PostMapping("/auditApply")
    @PreAuthorize("@pms.hasPermission('seckill:seckill:auditApply')")
    @Operation(summary =  "秒杀活动提交审核")
    public ServerResponseEntity<Void> auditApply(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Seckill seckill = seckillService.getById(offlineHandleEventAuditParam.getHandleId());
        if (seckill == null) {
            // 未找到此活动，请稍后重试
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        seckillService.auditApply(offlineHandleEventAuditParam.getEventId(), offlineHandleEventAuditParam.getHandleId(), offlineHandleEventAuditParam.getReapplyReason());
        // 移除缓存
        seckillService.removeSeckillCache(seckill.getSeckillId(), seckill.getProdId());
        eventPublisher.publishEvent(new EsProductUpdateEvent(seckill.getProdId(), null, EsOperationType.UPDATE));
        return ServerResponseEntity.success();
    }
}
